package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class QuanZiApiService {

    @Autowired
    private UserService userService;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Autowired
    private PicUploadService picUploadService;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    public Object queryPublishList(Integer page, Integer pageSzie) {
        Long userId = UserThreadLocal.get();
        if(userId == null) {
            return null;
        }

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSzie);
        pageResult.setPage(page);

        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSzie);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = fillPublishList(records);

        pageResult.setItems(quanZiVoList);

        return pageResult;
    }

    private List<QuanZiVo> fillPublishList(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        for (Publish publish : records) {
            QuanZiVo quanZiVo = BeanUtil.toBeanIgnoreError(publish, QuanZiVo.class);
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVo.setDistance("距离1.8公里"); //TODO 距离

            quanZiVo.setCommentCount(this.quanZiApi.queryCommentCount(publish.getId())); //TODO 评论数
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(UserThreadLocal.get(), publish.getId().toHexString()) ? 1 : 0); //TODO 是否点赞（1是，0否）
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(publish.getId().toHexString()))); //TODO 点赞数
            quanZiVo.setHasLoved(Convert.toInt(this.quanZiApi.queryUserIsLove(UserThreadLocal.get(), publish.getId().toHexString()))); //TODO 是否喜欢（1是，0否）
            if(!ObjectUtil.isEmpty(this.quanZiApi.queryLoveCount(publish.getId().toHexString()))) {
                quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(publish.getId().toHexString()))); //TODO 喜欢数
            } else {
                quanZiVo.setLoveCount(0);
            }
            quanZiVoList.add(quanZiVo);
        }

        List<Object> userIdList = CollUtil.getFieldValues(quanZiVoList, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equal(userInfo.getUserId(), quanZiVo.getUserId())) {
                    BeanUtil.copyProperties(userInfo, quanZiVo, "id");
                    quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
                    break;
                }
            }
        }
        return quanZiVoList;
    }

    public Object savePublish(String textContent, String location,
                              String latitude, String longitude, MultipartFile[] multipartFile) {
        Publish publish = new Publish();
        publish.setUserId(UserThreadLocal.get());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setMedias(new ArrayList<>());

        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult uploadResult = this.picUploadService.upload(file);
            if (StrUtil.isNotEmpty(uploadResult.getName())) {
                publish.getMedias().add(uploadResult.getName());
            }
        }

        String publishId = this.quanZiApi.savePublish(publish);
        if (StrUtil.isEmpty(publishId)) {
            return ErrorResult.builder().errCode("500").errMessage("发布动态失效！").build();
        }

        return null;
    }

    public Object queryRecommendPublish(Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        Long userId = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = fillPublishList(records);
        pageResult.setItems(quanZiVoList);

        return pageResult;
    }

    public Long likeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        //点赞
        Boolean result = this.quanZiApi.likeComment(userId, publishId);
        if (result) {
            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return 0L;
    }

    public Long disLikeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        //取消点赞
        Boolean result = this.quanZiApi.disLikeComment(userId, publishId);
        if (result) {
            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return 0L;
    }

    public Long loveCommet(String publishId) {
        Long userId = UserThreadLocal.get();
        Boolean isSuccess = this.quanZiApi.loveComment(userId, publishId);
        if(isSuccess) {
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return 0L;
    }

    public Long unLoveCommet(String publishId) {

        Long userId = UserThreadLocal.get();
        Boolean isSuccess = this.quanZiApi.disLoveComment(userId, publishId);
        if(isSuccess) {
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return 0L;
    }

    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if(!ObjectUtil.isEmpty(publish)) {
            return this.fillPublishList(Arrays.asList(publish)).get(0);
        }
        return null;
    }

    public PageResult getCommentList(String movementId, String page, String pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(Convert.toInt(page));
        pageResult.setPagesize(Convert.toInt(pageSize));
        pageResult.setCounts(this.quanZiApi.queryCommentCount(new ObjectId(movementId)));

        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(movementId, Convert.toInt(page), Convert.toInt(pageSize));
        if(ObjectUtil.isEmpty(pageInfo.getRecords())) {
            return pageResult;
        }

        List<CommentVo> commentVoList = new ArrayList<>();
        List<Comment> comments = pageInfo.getRecords();
        for (Comment comment : comments) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(comment.getId().toHexString());
            Long userId = comment.getUserId();
            UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
            commentVo.setContent(comment.getContent());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            commentVo.setCreateDate(sdf.format(new Date(comment.getCreated())));

            Long likeCount = this.quanZiApi.queryLikeCount(Convert.toStr(comment.getId()));
            if(ObjectUtil.isEmpty(likeCount)) {
                commentVo.setLikeCount(0);
            } else {
                commentVo.setLikeCount(Convert.toInt(likeCount));
            }

            Boolean isLike = this.quanZiApi.queryUserIsLike(userId, commentVo.getId());
            if(ObjectUtil.isEmpty(isLike) || ObjectUtil.equal(isLike, false)) {
                commentVo.setHasLiked(0);
            } else {
                commentVo.setHasLiked(1);
            }
            commentVoList.add(commentVo);
        }

        pageResult.setItems(commentVoList);

        return pageResult;
    }

    public Boolean saveComment(String publishId, String content) {
        Long userId = UserThreadLocal.get();
        Boolean isSuccess = this.quanZiApi.saveComment(userId, publishId, content);
        return isSuccess;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        pageResult.setItems(this.fillPublishList(records));
        return pageResult;
    }

    public List<VisitorsVo> queryVisitorsList() {
        Long userId = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(userId);
        if(CollUtil.isEmpty(visitorsList)){
            return Collections.emptyList();
        }

        //查询用户列表
        List<Object> userIdList = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        System.out.println("visitorsVoList = " + visitorsVoList);

        for (Object uId : userIdList) {
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equal(uId, userInfo.getUserId())) {
                    VisitorsVo visitorsVo = BeanUtil.toBeanIgnoreError(userInfo, VisitorsVo.class);
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;

    }
}
